package design_pattern.study;

public class Singleton {
    public static void main(String[] args) {
        Singleton1 instance = Singleton1.INSTANCE;
        Singleton1 instance1 = Singleton1.INSTANCE;
        System.out.println(instance  == instance1);
        System.out.println(instance.hashCode() == instance1.hashCode());
        instance.sayOk();
    }
    /**
     * 饿汉式1
     */
    private Singleton(){

    }
    private static final Singleton singleton = new Singleton();
    public static Singleton getInstance(){
        return singleton;
    }
    /**
     * 饿汉式2
     */
    private static Singleton singleton1;
    static {
        singleton1 = new Singleton();
    }
    public static Singleton getInstance1(){
        return singleton1;
    }
    /**
     * 懒汉式1 双检锁写法
     */
    private static volatile Singleton singleton2;
    public static Singleton getInstance2(){
        if(singleton2 == null){
            synchronized (Singleton.class){
                if (singleton2 == null){
                    singleton2 = new Singleton();
                }
            }
        }
        return singleton2;
    }
    /**
     * 懒汉式2 静态内部类方式
     */
    private static class SingletonInstance{
        private static final Singleton SINGLETON = new Singleton();
    }
    private static Singleton getInstance3(){
        return SingletonInstance.SINGLETON;
    }
}
enum Singleton1{
    /**
     * 实例化 单例方式 相当于无参构造实例化
     */
    INSTANCE;
    public void sayOk(){
        System.out.println("ok");
    }
}